// CommonJS
const { app, BrowserWindow, ipcMain, screen, Tray, Menu, dialog, shell, Notification, globalShortcut } = require('electron');
const path = require("path");
const { exec } = require('child_process');
const screenshotHandler = require('../src/utils/screenshot')
const DialogManager = require('../src/utils/dialogManager');
// 屏蔽安全警告
process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = process.env.NODE_ENV === 'production' ? 'false' : 'true'

let win;
let isMinimized = false;
let originalBounds;
let appTray = null; // 在外面创建 tray ，防止被自动删除，导致图标消失
// 创建浏览器窗口时，调用这个函数。
const createWindow = () => {
  const isDev = !!process.env.VITE_DEV_SERVER_URL;
  win = new BrowserWindow({
    width: 800,
    height: 600,
    frame: false,  //顶部菜单显隐 必须关闭才有透明效果
    transparent: true,
    backgroundColor: "rgba(0, 0, 0, 0.45)",
    movable: true,
    resizable: true,
    icon: path.join(__dirname, '../public/logo.ico'),
    webPreferences: {
      webSecurity: process.env.NODE_ENV === 'production', // 允许跨协议请求
      allowRunningInsecureContent: isDev,  // 允许混合内容
      nodeIntegration: true,  // 集成node api
      contextIsolation: true, // 启用上下文隔离（安全！）
      webviewTag: true,
      preload: path.join(__dirname, "preload.js"),
    },
  })
  // development模式
  if(isDev) {
    win.loadURL(process.env.VITE_DEV_SERVER_URL)
    // 开启调试台
    win.webContents.openDevTools()
  }else {
    win.loadFile(path.join(__dirname, '../dist/index.html'))
  }
  setupTray()
}

const setupTray = () => {
  const trayMenuTemplate = [
    {
      label: "打开应用",
      click: function () {
        win.show();
      }
    },
    {
      label: "应用设置",
      click: function () {}
    },
    {
      label: "退出应用",
      click: function () {
        app.quit();
      }
    },
  ];
  let iconPath = path.join(__dirname, "../public/logo.ico");
  appTray = appTray || new Tray(iconPath);
  const contextMenu = Menu.buildFromTemplate(trayMenuTemplate);
  appTray.setContextMenu(contextMenu);
  appTray.setToolTip('管小花');

  const handleTrayClick = () => {
    win.setAlwaysOnTop(true, 'floating');
    win.show();

    const blurHandler = () => {
      win.setAlwaysOnTop(false);
      win.off('blur', blurHandler); // 解绑自身
    };
    win.off('blur', blurHandler);
    win.on('blur', blurHandler);
  }
  appTray.removeAllListeners('click');
  appTray.on('click', handleTrayClick);
}

// 新增悬浮球窗口相关代码
let floatWindow = null
const createFloatWindow = () => {
  floatWindow = new BrowserWindow({
    frame: false,
    transparent: true,
    backgroundColor: "rgba(0, 0, 0, 0.45)",
    resizable: false,
    movable: true,
    alwaysOnTop: true,
    webPreferences: {
      webSecurity: process.env.NODE_ENV === 'production', // 允许跨协议请求
      nodeIntegration: true,  // 集成node api
      contextIsolation: true, // 启用上下文隔离（安全！）必须，不然通信preload无效
      webviewTag: true,
      preload: path.join(__dirname, "preload.js"),
    },
  })
  // 加载悬浮球页面
  if (process.env.VITE_DEV_SERVER_URL) {
    floatWindow.loadURL(process.env.VITE_DEV_SERVER_URL + '#/float')
    floatWindow.webContents.openDevTools()
  } else {
    floatWindow.loadFile(path.join(__dirname, '../dist/index.html'), { hash: '#/float' })
  }

  // 实现可拖动
  let isDragging = false;
  let currentPosition = { x: 0, y: 0 };

  floatWindow.webContents.on('ipc-message', (_, message) => {
    if (message === 'drag-start') {
      isDragging = true;
      const [x, y] = floatWindow.getPosition();
      currentPosition = { x, y };
    }
    if (message === 'drag-end') isDragging = false;
  });

  floatWindow.on('closed', () => floatWindow = null);
}

// Electron 会在初始化后并准备
app.whenReady().then(() => {
  createWindow()
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

app.on('ready', () => {
  let ret = globalShortcut.register('ctrl + q', () => {
    // 按下快捷键的后续操作
    console.log('ctrl + q is pressed')
  })
  if (!ret) {
    console.log('register globalShortcut failed')
    return false
  }
})

// 注销快捷键
app.on('will-quit', () => {
  globalShortcut.unregister('ctrl + q') // 注销某一个全局快捷键
  globalShortcut.unregisterAll() // 注销所有快捷键
})

/**
 * dialog 公共模块
 * showError 错误提示
 * openFile 打开文件
 * saveFile 保存文件
 * showMessage 消息提示
 * */
ipcMain.on('showError', (event,data) => {
  DialogManager.showErrorDialog(data.title, data.content)
})

ipcMain.on('openFile', (event,data) => {
  console.log(data);
  DialogManager.openFileDialog(data).then(res => {
    console.log(res)
  })
})

ipcMain.on('saveFile', (event, data) => {
  DialogManager.showSaveDialog(data).then(res => {
    console.log(res)
  })
})

ipcMain.on('showMessage', (event, data) => {
  DialogManager.showMessage(data).then(res => {
    console.log(res)
  })
})

ipcMain.on('test', (event, data) => {
  // Notification不生效
  const NOTIFICATION_TITLE = 'Basic Notification'
  const NOTIFICATION_BODY = 'Notification from the Main process'
  console.log(11111)
  new Notification({
    title: NOTIFICATION_TITLE,
    body: NOTIFICATION_BODY
  }).show()
})

/**
 * 退出应用
* */
ipcMain.on('quit', () => {
  DialogManager.showMessage({
    type: 'info',
    title : '确认',
    message: '确定要退出应用程序吗？',
    buttons: ['取消', '确定'],
  }).then(res => {
    if (res.response === 1){
      app.quit()
    }
  })
})
/**
 * 暂未开发功能
 * */
ipcMain.on('notOpen', () => {
  DialogManager.showMessage({
    message: '该功能暂未开放，敬请期待！'
  }).then(res =>{ })
})
/**
 * 窗口最大最小切换
 * */
ipcMain.on('toggleWindow', () => {
  const { width, height } = screen.getPrimaryDisplay().workAreaSize; // 获取屏幕的宽度和高度
  console.log(isMinimized, win.getBounds())
  if (!isMinimized) {
    originalBounds = win.getBounds();
    // 设置新尺寸和位置
    const newWidth = 410; // 收起后的宽度
    const newHeight = 500; // 收起后的高度
    win.setBounds({
      x: width - newWidth - 50,
      y: 100,
      width: newWidth,
      height: newHeight
    });

    // 窗口置顶并去掉边框
    // win.setAlwaysOnTop(true);
  } else {
    // 恢复原始状态
    win.setBounds(originalBounds);
    win.center()
  }
  isMinimized = !isMinimized;
})
/**
 * 添加高度调整监听
 * */
ipcMain.on('adjust-height', (event, height) => {
  const [currentWidth] = win.getSize()
  win.setSize(currentWidth, Math.floor(height), true)
})
/**
 * 最小化到托盘
* */
ipcMain.on('goTray', (event, data) => {
  win.hide()
})
/**
 * 截屏
 * */
ipcMain.on('screenShots', () => {
  if (process.platform === 'darwin') { // macOS
    screenshotHandler.handleScreenShots(win)
  } else {
    screenshotHandler.screenWindow(win)
  }
})

async function handleFileOpen () {
  const { canceled, filePaths } = await dialog.showOpenDialog(
    {
      title: '选择文件66666',
      properties: ['openFile', 'multiSelections']
    })
  if (!canceled) {
    return filePaths[0]
  }
}
/**
 * 选择文件
 * */
ipcMain.handle('chooseFile', () => {
  const { canceled, filePaths } = dialog.showOpenDialog(
    {
      title: '选择文件',
      properties: ['openFile', 'multiSelections']
    })
  if (!canceled) {
    return filePaths[0]
  }
})
/**
 * 默认浏览器打开链接
* */
ipcMain.on('goLink', (event, data) => {
  shell.openExternal(data).then(res => {})
})
/**
 * 打开计算器
 * */
ipcMain.on('calculator', () => {
  let command;
  switch (process.platform) {
    case 'win32':
      command = 'calc.exe';
      break;
    case 'darwin':
      command = 'open /System/Applications/Calculator.app';
      break;
    case 'linux':
      command = 'gnome-calculator || kde-calculator || xdg-open calculator:'; // 多尝试几种方法
      break;
    default:
      console.error('Unsupported platform');
      return;
  }
  exec(command, (error) => {
    if (error) {
      DialogManager.showErrorDialog('提示', '无法打开计算器')
    }
  });
})

/**
 * 切换背景色
* */
ipcMain.on('changeBgColor', (event, data) => {
  console.log(data)
  win.setBackgroundColor(data)
  console.log(win.getBackgroundColor())
})

/**
 * 悬浮球切换
 * */
ipcMain.on('showFloatBall', (event,bounds) => {
  const { workAreaSize } = screen.getPrimaryDisplay()
  if (bounds.turnIntoABall) {
    win.hide();
    // 创建或显示悬浮窗
    if (!floatWindow || floatWindow.isDestroyed()) {
      createFloatWindow();
    } else {
      floatWindow.show();
    }
    // 设置悬浮窗位置
    floatWindow.setBounds({
      x: workAreaSize.width - 300,
      y: workAreaSize.height - 300,
      width: 200,
      height: 200
    });
  } else {
    // 显示主窗口
    win.show();
    if (floatWindow) floatWindow.hide();
  }
})

/**
 * 拖动悬浮球方法
 * */

ipcMain.handle('getScreenInfo', () => {
  const { workAreaSize, size } = screen.getPrimaryDisplay();
  return {
    workAreaSize,
    size,
  };
});

ipcMain.handle('getPosition', (event, data) => {
  if (floatWindow && !floatWindow.isDestroyed()) {
    const [x, y] = floatWindow.getPosition();
    console.log(x, y)
    return { x, y };
  }
  return { x: 0, y: 0 }; // 默认值
})

ipcMain.on('setPosition', (event, { x, y }) => {
  if (floatWindow && !floatWindow.isDestroyed()) {
    // 获取屏幕边界
    const { workAreaSize } = screen.getPrimaryDisplay();
    const maxX = workAreaSize.width - 50; // 悬浮球宽度
    const maxY = workAreaSize.height - 50;

    // 限制位置
    const clampedX = Math.max(0, Math.min(x, maxX));
    const clampedY = Math.max(0, Math.min(y, maxY));

    floatWindow.setPosition(clampedX, clampedY);
  }
})

ipcMain.handle('get-window-size', () => {
  if (floatWindow && !floatWindow.isDestroyed()) {
    const size = floatWindow.getSize();
    return size;
  }
  return [200, 200]; // 默认尺寸
});
